import { defineStore } from 'pinia'
import { getUserInfo,login,register,changePassword } from '@/apis/users/api.js'

export const useUserStore = defineStore('user', {
  state: () => ({
    username: '',
    avatar: '',
    token: localStorage.getItem('token') || ''
  }),
  
  actions: {
    // 注册
    async register(userData) {
      const data = await register(userData)
    },

    // 登录
    async login(userData) {
      const data = await login(userData)
      this.username = data.username;
      this.setToken(data.access_token)
    },

    // 登出
    async logout() {
      this.clearUserInfo()
    },

    // 修改密码
    async updatePassword(data) {
      const res = await updatePassword(data)
    },

    // 获取用户信息
    async fetchUserInfo() {
      const { data } = await getUserInfo()
      console.log(data)
      this.username = data.username
      // this.avatar = data.avatar
    },
    
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
    },
    
    clearUserInfo() {
      this.username = ''
      this.avatar = ''
      this.token = ''
      localStorage.removeItem('token')
    }
  }
})
